import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';
import type { ChatSession, UpdateChatSessionRequest } from '@/types/chat';
import { Prisma } from '@prisma/client';

// POST /api/client/chat/sessions/update - 更新聊天会话
async function handlePost(request: NextRequest): Promise<ChatSession> {
  // 1. 权限验证
  const authResult = await authenticateRequest(request);
  if (!authResult.success) {
    throw new Error(authResult.error || '认证失败');
  }

  // 2. 获取当前用户ID
  const userId = authResult.user?.id;
  if (!userId) {
    throw new Error('用户信息不存在');
  }

  // 3. 解析参数
  const body: UpdateChatSessionRequest & { chatId: string } = await request.json();
  const { chatId, title } = body;

  if (!chatId) {
    throw new Error('聊天会话ID为必填项');
  }

  // 4. 查找聊天会话
  const chatSession = await prisma.chatSession.findFirst({
    where: {
      chatId,
      userId: userId
    }
  });

  if (!chatSession) {
    throw new Error('聊天会话不存在');
  }

  // 5. 构建更新数据
  const updateData: Prisma.ChatSessionUpdateInput = {
    updatedAt: new Date()
  };

  if (title !== undefined) {
    updateData.title = title;
  }

  // 6. 更新聊天会话
  const updatedSession = await prisma.chatSession.update({
    where: { id: chatSession.id },
    data: updateData
  });

  // 7. 数据转换
  return {
    id: updatedSession.id,
    chatId: updatedSession.chatId,
    title: updatedSession.title || '新对话',
    userId: updatedSession.userId,
    createdAt: updatedSession.createdAt.toISOString(),
    updatedAt: updatedSession.updatedAt.toISOString(),
    messageCount: 0 // 这里可以根据需要调整
  };
}

export const POST = withMiddleware(handlePost);
